package com.ruoyi.finance.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.finance.domain.Merchant;
import com.ruoyi.finance.domain.PayOrder;
import com.ruoyi.finance.mapper.MerchantMapper;
import com.ruoyi.finance.mapper.PayOrderMapper;
import com.ruoyi.finance.service.IPayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * 支付订单Service业务层处理
 *
 * @author zt
 * @date 2023-11-15
 */
@Service
public class PayOrderServiceImpl implements IPayOrderService
{
    @Autowired
    private PayOrderMapper payOrderMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    /**
     * 查询支付订单
     *
     * @param outTradeNo 支付订单主键
     * @return 支付订单
     */
    @Override
    public PayOrder selectPayOrderByOutTradeNo(String outTradeNo)
    {
        PayOrder payOrder = new PayOrder();
        payOrder.setOutTradeNo(outTradeNo);
        payOrder.setTradeState("SUCCESS");
        return payOrderMapper.selectPayOrderOne(payOrder);
    }

    /**
     * 查询支付订单列表
     *
     * @param payOrder 支付订单
     * @return 支付订单
     */
    @Override
    public List<PayOrder> selectPayOrderList(PayOrder payOrder)
    {
        return payOrderMapper.selectPayOrderList(payOrder);
    }

    /**
     * 新增支付订单
     *
     * @param payOrder 支付订单
     * @return 结果
     */
    @Override
    public int insertPayOrder(PayOrder payOrder)
    {
        payOrder.setCreateTime(DateUtils.getNowDate());
        return payOrderMapper.insertPayOrder(payOrder);
    }

    @Override
    @Transactional
    public int updatePayOrderStatus(Map<String, String> map) throws ParseException {
        String out_trade_no = map.get("out_trade_no");
        String total_fee = map.get("total_fee");
        String transaction_id = map.get("transaction_id");
        String openid = map.get("openid");
        String time_end = map.get("time_end");
        String userId = map.get("attach");
        // 修改状态为已支付
        int success = this.updatePayOrder(new PayOrder(out_trade_no,openid,transaction_id,
                "SUCCESS",new SimpleDateFormat ("yyyyMMddHHmmss").parse(time_end)));
        // 为商户充值余额
        Float f = Float.valueOf(total_fee)/100;
        int i = merchantMapper.addBalance(new Merchant(Long.parseLong(userId), BigDecimal.valueOf(f)));
        return success+i;
    }

    /**
     * 修改支付订单
     *
     * @param payOrder 支付订单
     * @return 结果
     */
    @Override
    public int updatePayOrder(PayOrder payOrder)
    {
        return payOrderMapper.updatePayOrder(payOrder);
    }

}
